// ==UserScript==
// @name         Geocaching: Google Maps Button
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  Adds a Google Maps button next to cache coordinates on geocaching.com
// @match        https://www.geocaching.com/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    const coordRegex = /(N|S)\s*\d{1,2}[°\s]\s*\d{1,2}(?:\.\d+)?['\s]?\s*(E|W)\s*\d{1,3}[°\s]\s*\d{1,2}(?:\.\d+)?/i;

    function findCoordinateNode() {
        return document.querySelector(".coord-info .coordinates, #uxLatLon, .CacheDetailNavigationWidget .coordinates");
    }

    function findCoordinates() {
        const coordNode = findCoordinateNode();
        if (!coordNode) return null;

        const text = coordNode.innerText.trim();
        const match = text.match(coordRegex);

        return match ? match[0] : null;
    }

    function createButton(coords) {
        if (document.getElementById("btnGoogleMaps")) return;

        const coordNode = findCoordinateNode();
        if (!coordNode || !coordNode.parentNode) return;

        const btn = document.createElement("input");
        btn.type = "submit";
        btn.id = "btnGoogleMaps";
        btn.value = "Google Maps";
        btn.style.marginLeft = "10px";
        btn.style.color = "white";
        btn.style.background = "#4285F4";
        btn.style.border = "1px solid #2a56c6";
        btn.style.borderRadius = "4px";
        btn.style.padding = "4px 10px";
        btn.style.cursor = "pointer";
        btn.setAttribute("onclick", "return false;");

        btn.addEventListener("click", function () {
            const url =
                "https://www.google.com/maps/search/?api=1&query=" +
                encodeURIComponent(coords);

            window.open(url, "_blank", "noopener,noreferrer");
        });

        coordNode.parentNode.appendChild(btn);
    }

    function init() {
        const coords = findCoordinates();
        if (coords) createButton(coords);
    }

    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", init);
    } else {
        init();
    }

    const observer = new MutationObserver(init);
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

})();